package com.zoke.dappstore.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.SuperKotlin.pictureviewer.ImagePagerActivity;
import com.SuperKotlin.pictureviewer.PictureConfig;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadEntity;
import com.arialyy.aria.core.download.DownloadTask;
import com.arialyy.aria.core.download.DownloadTaskEntity;
import com.arialyy.aria.core.inf.IEntity;
import com.google.gson.Gson;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.zoke.dappstore.Conf;
import com.zoke.dappstore.R;
import com.zoke.dappstore.adapter.CommentAdapter;
import com.zoke.dappstore.adapter.ImageAdapter;
import com.zoke.dappstore.base.NebActivity;
import com.zoke.dappstore.model.Comment;
import com.zoke.dappstore.model.Dapp;
import com.zoke.dappstore.tools.Tools;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.zhanghai.android.materialratingbar.MaterialRatingBar;

@ContentView(R.layout.activity_dapp_detail)
public class DappDetailActivity extends NebActivity {

    public static void open(Activity activity, Dapp dapp) {
        Intent intent = new Intent(activity, DappDetailActivity.class);
        String json = new Gson().toJson(dapp);
        intent.putExtra("json", json);
        activity.startActivity(intent);
    }

    private Dapp mDapp;

    @ViewInject(R.id.recycler)
    private RecyclerView recyclerView;

    private CommentAdapter adapter;
    private List<Comment> mList = new ArrayList<>();

    private View mHeaderView;

    private TextView tv_empty;
    private ImageView headIv;
    private TextView tv_title;
    private TextView tv_address;
    @ViewInject(R.id.progress)
    private ProgressBar progress;
    @ViewInject(R.id.tv_download)
    private TextView tv_download;

    private DownloadTask downloadTask;


    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String json = getIntent().getStringExtra("json");
        mDapp = new Gson().fromJson(json, Dapp.class);
        initTitle();
        adapter = new CommentAdapter(mList);
        adapter.openLoadAnimation();
        initHeaderView();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(adapter);
        if (mDapp.comment != null && mDapp.comment.size() != 0) {
            mList.addAll(mDapp.comment);
            adapter.notifyDataSetChanged();
        }
        Aria.download(this).register();
        doBtnState();
    }


    private void doBtnState() {
        DownloadTaskEntity entity = Aria.download(this).getDownloadTask(mDapp.apkUrl);
        if (entity == null) {
            return;
        }
        switch (entity.getState()) {
            case IEntity.STATE_WAIT:
            case IEntity.STATE_OTHER:
            case IEntity.STATE_FAIL:
            case IEntity.STATE_CANCEL:
                tv_download.setText("点击下载");
                break;
            case IEntity.STATE_STOP:
                tv_download.setText("继续");
                break;
            case IEntity.STATE_PRE:
            case IEntity.STATE_POST_PRE:
            case IEntity.STATE_RUNNING:
                tv_download.setText("下载中");
                tv_download.setBackgroundResource(R.drawable.shape_btn_2);
                break;
            case IEntity.STATE_COMPLETE:
                tv_download.setText("点击安装");
                tv_download.setBackgroundResource(R.drawable.shape_btn_1);
                break;
        }
    }


    private void initTitle() {
        mTitleBar.setTitle("应用详情");
        mTitleBar.setLeft(R.drawable.ic_back, null);
        mTitleBar.setRight(R.drawable.ic_edit, v -> AddActivity.open(DappDetailActivity.this, mDapp.id));
    }

    @Event({R.id.tv_download})
    private void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.tv_download:
                doClickDownload();
                break;
        }
    }

    private void doClickDownload() {
        DownloadTaskEntity entity = Aria.download(this).getDownloadTask(mDapp.apkUrl);
        if (entity == null) {
            download();
            return;
        }
        switch (entity.getState()) {
            case IEntity.STATE_WAIT:
            case IEntity.STATE_OTHER:
            case IEntity.STATE_FAIL:
            case IEntity.STATE_CANCEL:
                tv_download.setText("点击下载");
                download();
                break;
            case IEntity.STATE_STOP:
//                tv_download.setText("暂停");
                tv_download.setText("继续");
                tv_download.setBackgroundResource(R.drawable.shape_btn_2);
                if (downloadTask != null) downloadTask.start();
                break;
            case IEntity.STATE_PRE:
            case IEntity.STATE_POST_PRE:
            case IEntity.STATE_RUNNING:
                tv_download.setText("下载中");
//                if (downloadTask != null) downloadTask.stop();
                break;
            case IEntity.STATE_COMPLETE:
                tv_download.setText("点击安装");
                tv_download.setBackgroundResource(R.drawable.shape_btn_1);
                DownloadEntity downloadEntity = entity.getEntity();
                if (downloadEntity != null) {
                    String downloadPath = downloadEntity.getDownloadPath();
                    Tools.install(DappDetailActivity.this, downloadPath);
                }
                break;
        }
    }

    private void download() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.Group.STORAGE)
                .onGranted(permissions -> {
                    // Storage permission are allowed.
                    Aria.download(this)
                            .load(mDapp.apkUrl)     //读取下载地址
                            .setFilePath(Tools.getFilePath(mDapp.apkname))
                            .setExtendField(new Gson().toJson(mDapp))
                            .start();   //启动下载
                })
                .onDenied(permissions -> {
                    // Storage permission are not allowed.
                })
                .start();
    }


    private void initHeaderView() {
        mHeaderView = View.inflate(this, R.layout.include_header, null);
        adapter.setHeaderView(mHeaderView);
        tv_empty = mHeaderView.findViewById(R.id.tv_empty);
        tv_empty.setVisibility(mDapp.comment != null && mDapp.comment.size() != 0 ? View.GONE : View.VISIBLE);
        headIv = mHeaderView.findViewById(R.id.headIv);
        //设置数据
        tv_title = mHeaderView.findViewById(R.id.tv_title);
        ImageOptions options = new ImageOptions.Builder()
                .setRadius(20)
                .build();

        x.image().bind(headIv, mDapp.icon, options);
        tv_title.setText(mDapp.name);
        if (mDapp.screenshot != null && mDapp.screenshot.size() != 0) {
            RecyclerView screenRecycler = mHeaderView.findViewById(R.id.screens);
            ImageAdapter imageAdapter = new ImageAdapter(mDapp.screenshot);
            screenRecycler.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
            imageAdapter.openLoadAnimation();
            screenRecycler.setAdapter(imageAdapter);
            imageAdapter.setOnItemClickListener((adapter, view, position) -> {
                //使用方式
                PictureConfig config = new PictureConfig.Builder()
                        .setListData((ArrayList<String>) mDapp.screenshot)    //图片数据List<String> list
                        .setPosition(0)    //图片下标（从第position张图片开始浏览）
                        .setDownloadPath("dapp_screen_hot")    //图片下载文件夹地址
                        .setIsShowNumber(true)//是否显示数字下标
                        .needDownload(true)    //是否支持图片下载
                        .setPlacrHolder(R.mipmap.ic_logo)    //占位符图片（图片加载完成前显示的资源图片，来源drawable或者mipmap）
                        .build();
                ImagePagerActivity.startActivity(DappDetailActivity.this, config);
            });
        }
        TextView tv_des = mHeaderView.findViewById(R.id.tv_des);
        if (TextUtils.isEmpty(mDapp.des)) {
            mDapp.des = "这个作者很懒，应用描述都没有来得及写呢……";
        }
        tv_des.setText(mDapp.des);
        tv_address = mHeaderView.findViewById(R.id.tv_address);
        tv_address.setText(Html.fromHtml("合约地址：<u><font color=#45C01A>" + mDapp.contractAddress + "</font></u>"));
        TextView tv_update = mHeaderView.findViewById(R.id.tv_update);
        //后面格式化一下
        tv_update.setText("更新时间：" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(mDapp.updateTime))));
        TextView tv_auth = mHeaderView.findViewById(R.id.tv_auth);
        tv_auth.setText("开发作者：" + mDapp.author);
        TextView tv_version = mHeaderView.findViewById(R.id.tv_version);
        tv_version.setText("版本要求：" + mDapp.minsdkversion);
        MaterialRatingBar rb = mHeaderView.findViewById(R.id.rb);
        rb.setIsIndicator(true);
        rb.setProgress(mDapp.score * 2);
        TextView tv_score = mHeaderView.findViewById(R.id.tv_score);
        int size = 0;
        if (mDapp.comment != null && mDapp.comment.size() != 0) {
            size = mDapp.comment.size();
        }
        tv_score.setText(mDapp.score + "分（共" + size + "人评）");

        TextView tv_size = mHeaderView.findViewById(R.id.tv_size);
        String typeName;
        switch (mDapp.type) {
            case 1:
                typeName = "应用";
                break;
            case 2:
                typeName = "游戏";
                break;
            default:
                typeName = "其他";
                break;
        }
        if (!TextUtils.isEmpty(mDapp.subType)) {
            typeName = mDapp.subType;
        }
        tv_size.setText(typeName + " | " + Tools.formatSize(mDapp.size));
        getHashByAddress(mDapp.contractAddress);
    }

    private void getHashByAddress(String contractAddress) {
        String json = "{\"address\":\"" + contractAddress + "\"}";
        RequestParams params = new RequestParams("https://mainnet.nebulas.io/v1/user/getTransactionByContract");
        params.setAsJsonContent(true);
        params.setBodyContent(json);
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                LogUtil.e(result);
                try {
                    JSONObject jo = new JSONObject(result);
                    JSONObject res = jo.getJSONObject("result");
                    final String hash = res.optString("hash");
                    tv_address.setOnClickListener(v -> {
                        Intent intent = new Intent(DappDetailActivity.this, WebActivity.class);
                        intent.putExtra("url", Conf.EXPO + hash);
                        DappDetailActivity.this.startActivity(intent);
                    });
                } catch (JSONException e) {
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        initBar(R.id.status, false);
    }

    @Download.onTaskPre
    void taskPre(DownloadTask task) {
        downloadTask = task;
        LogUtil.e("taskPre");
        if (task.getKey().equals(mDapp.apkUrl)) {
            tv_download.setText("继续");
            tv_download.setBackgroundResource(R.drawable.shape_btn_2);
        }
    }

    //在这里处理任务执行中的状态，如进度进度条的刷新
    @Download.onTaskRunning
    protected void running(DownloadTask task) {
        downloadTask = task;
        if (task.getKey().equals(mDapp.apkUrl)) {
//            可以通过url判断是否是指定任务的回调
            int p = task.getPercent();    //任务进度百分比
            String speed = task.getConvertSpeed();    //转换单位后的下载速度，单位转换需要在配置文件中打开
            long speed1 = task.getSpeed(); //原始byte长度速度
            LogUtil.e("p =" + p + ";speed=" + speed + ";speed1=" + speed1);
            progress.setProgress(p);
        }

    }

    @Download.onTaskComplete
    void taskComplete(DownloadTask task) {
        //在这里处理任务完成的状态
        if (task.getKey().equals(mDapp.apkUrl)) {
            tv_download.setText("点击安装");
            tv_download.setBackgroundResource(R.drawable.shape_btn_1);
            String downloadPath = task.getDownloadPath();
            LogUtil.e("下载完成了:" + downloadPath);
            Tools.install(DappDetailActivity.this, downloadPath);
        }

    }
}
